<script setup>
import {onMounted, ref} from "vue";
import {ImageFeatureDB} from '@/api/db/indexDb.js'
import {ImageAlgorithms} from '@/utils/algorithm.js'
import {ClipboardManager} from '@/utils/clipboard.js'
import {BatchProcessor} from '@/utils/batchProcessor.js'

const getElement = (id) => document.getElementById(id);
const pastedImages = {
  library: ref(null),
  search: ref(null)
};

const algorithms = ref(null);
const clipboardManager = ref(null)
const db = ref(null)

const initialize = () => {
  algorithms.value = new ImageAlgorithms();
  db.value = new ImageFeatureDB();
  db.value.init();
  clipboardManager.value = new ClipboardManager();
  clipboardManager.value.init();
  // 注册剪贴板粘贴区域
  clipboardManager.value.registerPasteArea('searchPasteArea', (blob) => {
    handleSearchPaste(blob);
  });

  getElement('similarityThreshold').addEventListener('input', (e) => {
    getElement('thresholdValue').textContent = e.target.value + '%';
  });
};

const handleSearchPaste = async (blob) => {
  try {
    updateStatus('正在处理搜索图片...');

    // 创建预览
    const previewUrl = URL.createObjectURL(blob);
    getElement('searchPastePreview').innerHTML = `<img src="${previewUrl}" class="paste-preview" alt="预览">`;

    // 存储图片数据
    pastedImages.search.value = {
      blob: blob,
      previewUrl: previewUrl
    };

    updateStatus('搜索图片已就绪，可以点击"开始搜索"');

    const searchPastePreview = getElement('searchPastePreview');
    let searchBlob = null;
    // 检查是否有粘贴的搜索图片
    if (pastedImages.search.value) {
      searchBlob = pastedImages.search.value.blob;
      await handleSearchAndDisplay(searchBlob);
      // 清理预览
      // URL.revokeObjectURL(pastedImages.search.value.previewUrl);
      // pastedImages.search.value = null;
      // searchPastePreview.innerHTML = '';
    }


  } catch (error) {
    updateStatus('搜索图片处理失败: ' + error.message, true);
  }
}

const handleSelect = async (event) => {
  let searchBlob = null;
  // 使用传统文件选择
  const file = Array.from(event.target.files)[0];
  if (file) {
    searchBlob = file;
  }
  // 创建预览
  const previewUrl = URL.createObjectURL(searchBlob);
  getElement('searchPastePreview').innerHTML = `<img src="${previewUrl}" class="paste-preview" alt="预览">`;

  await handleSearchAndDisplay(searchBlob);

};

const displayResults = (results, algorithm) => {

  const resultsE = getElement('results');

  if (results.length === 0) {
    resultsE.innerHTML = '<div style="text-align: center; color: #666; padding: 20px;">未找到相似图片</div>';
    return;
  }

  const algorithmNames = {
    'colorHistogram': '颜色直方图',
    'perceptualHash': '感知哈希',
    'colorHash': '颜色哈希',
    'combined': '组合算法'
  };

  resultsE.innerHTML = `
            <div style="margin-bottom: 10px; font-weight: bold; color: #333;">
                算法: ${algorithmNames[algorithm]} | 显示: ${results.length} 个结果
            </div>
        `;

  results.forEach((item, index) => {
    const resultItem = document.createElement('div');
    resultItem.className = 'result-item';

    const similarityPercent = (item.similarity * 100).toFixed(1);
    const rankClass = index < 3 ? ` style="color: #ea4335; font-weight: bold;"` : "";

    resultItem.innerHTML = `
                <div class="thumbnail-container">
                    <img src="${item.thumbnail}" alt="${item.name}" class="thumbnail">
                    <div class="result-info">
                        <div>
                            <span${rankClass}>${index + 1}.</span>
                            ${item.name}
                        </div>
                        <div style="font-size: 12px; color: #666; margin: 2px 0;">
                            相似度: <strong>${similarityPercent}%</strong>
                        </div>
                        <div class="algorithm-info">
                            算法: ${algorithmNames[item.algorithm]}
                        </div>
                        <div class="similarity-bar">
                            <div class="similarity-fill" style="width: ${similarityPercent}%"></div>
                        </div>
                    </div>
                </div>
            `;

    resultsE.appendChild(resultItem);
  });
}

const handleSearchAndDisplay = async (searchBlob) => {

  const algorithmSelect = getElement('algorithmSelect');
  const resultCount = getElement('resultCount');
  const similarityThreshold = getElement('similarityThreshold');
  const results = getElement('results');
  const searchImage = getElement('searchImage');


  if (!searchBlob) {
    updateStatus('请选择要搜索的图片或粘贴图片', true);
    return;
  }

  const algorithm = algorithmSelect.value;
  const maxResults = parseInt(resultCount.value) || 5;
  const threshold = parseInt(similarityThreshold.value) / 100;

  updateStatus('正在分析搜索图片...');
  results.innerHTML = '';

  try {
    // 将Blob转换为Image
    const searchImg = await algorithms.value.createImageFromBlob(searchBlob);

    // 计算搜索图片的特征
    const searchFeatures = await Promise.all([
      algorithms.value.calculateColorHistogram(searchImg),
      algorithms.value.calculatePerceptualHash(searchImg),
      algorithms.value.calculateColorHash(searchImg)
    ]).then(([colorHistogram, perceptualHash, colorHash]) => ({
      colorHistogram, perceptualHash, colorHash
    }));

    // 获取所有图片特征并计算相似度
    const allImages = await db.value.getAllImages();
    const results = [];

    for (const image of allImages) {
      let similarity;
      let algorithmUsed = algorithm;

      switch (algorithm) {
        case 'colorHistogram':
          similarity = algorithms.value.compareColorHistograms(
              searchFeatures.colorHistogram,
              image.features.colorHistogram
          );
          break;

        case 'perceptualHash':
          similarity = algorithms.value.comparePerceptualHashes(
              searchFeatures.perceptualHash,
              image.features.perceptualHash
          );
          break;

        case 'colorHash':
          similarity = algorithms.value.compareColorHashes(
              searchFeatures.colorHash,
              image.features.colorHash
          );
          break;

        case 'combined':
          similarity = algorithms.value.compareCombined(
              searchFeatures,
              image.features
          );
          break;

        default:
          similarity = 0;
      }

      if (similarity >= threshold) {
        results.push({
          name: image.name,
          thumbnail: image.thumbnail,
          similarity: similarity,
          algorithm: algorithmUsed
        });
      }
    }

    // 按相似度排序并限制结果数量
    results.sort((a, b) => b.similarity - a.similarity);
    const finalResults = results.slice(0, maxResults);

    displayResults(finalResults, algorithm);
    updateStatus(`搜索完成！找到 ${finalResults.length} 个相似结果 (阈值: ${Math.round(threshold * 100)}%)`);

    // 清空文件选择
    searchImage.value = '';

  } catch (error) {
    updateStatus('搜索失败: ' + error.message, true);
    console.error('Search error:', error);
  }
};

const updateStatus = (message, isError = false) => {
  const status = getElement('status');
  status.textContent = message;
  status.style.color = isError ? '#ea4335' : '#333';
  console.log('Status:', message);
};

onMounted(() => {
  initialize();
});
</script>

<template>
  <div class="section">
    <h3>🔍 搜索相似图片</h3>

    <!-- 文件上传方式 -->
    <div class="upload-options">
      <label class="upload-option-btn">
        <div>📎 选择文件</div>
        <input type="file" id="searchImage" accept="image/*" class="hidden" @change="handleSelect">
      </label>
      <div class="upload-option-btn" id="pasteToSearchBtn">
        <div>📋 粘贴图片</div>
      </div>
    </div>

    <!-- 搜索图片粘贴区域 -->
    <div class="upload-area" id="searchPasteArea">
      <div class="upload-icon">🔍</div>
      <p><strong>粘贴要搜索的截图</strong></p>
      <p>点击此区域后按 Ctrl+V 粘贴要搜索的截图</p>
      <div id="searchPastePreview"></div>
    </div>

    <!--    <button id="searchBtn" @click="handleSearch">开始搜索</button>-->
  </div>
  <div class="section">
    <h3>⚙️ 搜索配置</h3>
    <div class="config-row">
      <span class="config-label">算法选择:</span>
      <select id="algorithmSelect">
        <option value="combined">组合算法 (推荐)</option>
        <option value="colorHistogram">颜色直方图</option>
        <option value="perceptualHash">感知哈希 (pHash)</option>
        <option value="colorHash">颜色哈希 (快速)</option>
      </select>
    </div>
    <div class="config-row">
      <span class="config-label">显示结果数量:</span>
      <input type="number" id="resultCount" min="1" max="20" value="5" style="width: 60px;">
    </div>
    <div class="config-row">
      <span class="config-label">相似度阈值:</span>
      <input type="range" id="similarityThreshold" min="0" max="100" value="30" style="width: 120px;cursor: pointer">
      <span id="thresholdValue">30%</span>
    </div>
  </div>
  <div class="section">
    <h3>📊 搜索结果</h3>
    <div id="libraryInfo"></div>
    <div id="results"></div>
  </div>
</template>

<style scoped>
.section {
  margin-bottom: 15px;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 5px;
  background: #fafafa;
}

h3 {
  margin-top: 0;
  color: #333;
  border-bottom: 1px solid #eee;
  padding-bottom: 5px;
}

button {
  margin: 5px;
  padding: 8px 12px;
  background: #4285f4;
  color: white;
  border: none;
  border-radius: 3px;
  cursor: pointer;
  font-size: 12px;
}

button:hover {
  background: #3367d6;
}

button:disabled {
  background: #ccc;
  cursor: not-allowed;
}

select, input {
  padding: 6px;
  border: 1px solid #ddd;
  border-radius: 3px;
  font-size: 12px;
}

#status, #results {
  margin-top: 10px;
  padding: 10px;
  background: white;
  border-radius: 3px;
  min-height: 20px;
  border: 1px solid #e0e0e0;
}

:deep(.result-item) {
  margin: 8px 0;
  padding: 8px;
  background: white;
  border-left: 4px solid #4285f4;
  border-radius: 3px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

:deep(.similarity-bar) {

  height: 6px;
  background: #e0e0e0;
  margin-top: 4px;
  border-radius: 3px;

}

:deep(.similarity-fill) {
  height: 100%;
  background: linear-gradient(90deg, #4285f4, #34a853);
  border-radius: 3px;
}

progress {
  width: 100%;
}

.config-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 8px 0;
}

.config-label {
  font-weight: bold;
  color: #555;
}

:deep(.thumbnail-container) {
  display: flex;
  align-items: center;
  gap: 12px;
}

.thumbnail {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 3px;
  border: 1px solid #e0e0e0;
}

:deep(.result-info) {
  flex: 1;
}

:deep(.algorithm-info) {
  font-size: 11px;
  color: #666;
  margin-top: 2px;
}

.clear-btn {
  background: #ea4335;
}

.clear-btn:hover {
  background: #d33426;
}

.upload-area {
  border: 2px dashed #ccc;
  border-radius: 8px;
  padding: 20px;
  text-align: center;
  margin: 10px 0;
  background: white;
  cursor: pointer;
  transition: all 0.3s;
}

.upload-area:hover, .upload-area.dragover {
  border-color: #4285f4;
  background: #f0f7ff;
}

.upload-area p {
  margin: 5px 0;
  color: #666;
}

.upload-area.active {
  border-color: #4285f4;
  background: #f0f7ff;
  box-shadow: 0 0 0 2px rgba(66, 133, 244, 0.2);
}

.upload-area:focus {
  border-color: #4285f4;
  background: #f0f7ff;
  outline: none;
}

.upload-icon {
  font-size: 24px;
  margin-bottom: 8px;
  color: #4285f4;
}

.upload-options {
  display: flex;
  gap: 10px;
  margin-top: 10px;
}

.upload-option-btn {
  flex: 1;
  padding: 8px;
  background: #f8f9fa;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;
}

.upload-option-btn:hover {
  background: #e8f0fe;
  border-color: #4285f4;
}

.filename-input {
  width: 100%;
  margin-top: 8px;
  padding: 6px;
  border: 1px solid #ddd;
  border-radius: 3px;
}

.paste-preview {
  max-width: 100%;
  max-height: 150px;
  margin-top: 10px;
  border-radius: 4px;
  border: 1px solid #e0e0e0;
}

.hidden {
  display: none;
}
</style>